package ${groupId}.${artifactIdProjectPackageName}.interceptor;


import ${groupId}.${artifactIdProjectPackageName}.common.result.ResultSet;
import ${groupId}.${artifactIdProjectPackageName}.scope.LoginInfoRequest;
import ${groupId}.${artifactIdProjectPackageName}.exception.DdlApiErrorCode;
import org.springframework.util.AntPathMatcher;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ${groupId}.${artifactIdProjectPackageName}.utils.JsonUtils;

/**
 * 需要登录的拦截
 * @author lwd
 * @date 2020/10/21 11:35
 */
@Component
public class NeedLoginInterceptor implements HandlerInterceptor {

    @Autowired
    LoginInfoRequest loginInfoRequest;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        if(antPathMatcher.match("/**/0/**",request.getRequestURI())){
            return true;
        }

        //这边判断登录信息是否存在 有效
        if(loginInfoRequest.getLoginInfo() != null){
            String referer = request.getHeader("Referer");
            if(StringUtils.isBlank(referer)){
                referer = "";
            }
            //其他情况属于未登录 重定向登录页面
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().print(JsonUtils.toJson(ResultSet.builderFail(${mainClassPrefix}ErrorCode.REDIRECT,referer)));
            return false;
        }


        return true;
    }

}